/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-06-29 18:54:28
 * @LastEditTime: 2022-07-06 19:49:58
 */

import { Key, useEffect, useState } from 'react';
import { Table, Typography } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { fetchDicItemListById } from '@/api/rulesettings/dictionary';
import { IMetadata } from '@/interfaces/metadata';

const { Paragraph, Text } = Typography;

interface IDictionarySettingProps {
  field: IMetadata;
  setSelectedItem: any;
}

const DictionarySetting = (props: IDictionarySettingProps) => {
  const { field, setSelectedItem } = props;

  const [loading, setLoading] = useState(false);
  // 表格数据
  const [list, setList] = useState([]);
  // 表格
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);

  // 字典表格选中的key
  const columns: ColumnsType = [
    {
      title: '序号',
      key: 'id',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '名称',
      key: 'name',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '代码',
      key: 'code',
      dataIndex: 'code',
      align: 'center'
    },
    {
      title: '值',
      key: 'value',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '描述',
      key: 'desc',
      dataIndex: 'desc',
      align: 'center'
    }
  ];

  useEffect(() => {
    setLoading(true);
    fetchDicItemListById(field.dict_type_id)
      .then((res) => {
        const { data } = res;
        setList(data);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedKeys: number[]) => {
    setSelectedRowKeys(selectedKeys);
    setSelectedItem(selectedKeys.map((id) => list.find((item) => item.id === id)));
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  };

  return (
    <>
      <Paragraph>
        <Text strong>字段：</Text>
        {field.field_desc}（选择字典表内的数据作为目录节点）
      </Paragraph>
      <Table
        loading={loading}
        columns={columns}
        dataSource={list}
        rowSelection={rowSelection}
        rowKey="id"
        size="small"
        bordered
      />
    </>
  );
};

export default DictionarySetting;
